package ljye.com.ljye.fragment;

import android.app.ActionBar;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.youth.banner.Banner;

import java.util.ArrayList;
import java.util.List;

import ljye.com.ljye.R;
import ljye.com.ljye.activity.Activity_Course_Details;
import ljye.com.ljye.activity.Activity_Institution_Home;
import ljye.com.ljye.activity.Activity_Search;
import ljye.com.ljye.activity.Activity_Teacher_Home;
import ljye.com.ljye.adapter.GridViewAdapter;
import ljye.com.ljye.adapter.Home_Star_Teacher_GridViewAdapter;
import ljye.com.ljye.adapter.LeftAdapter;
import ljye.com.ljye.adapter.Popular_Course_Adapter;
import ljye.com.ljye.adapter.RightAdapter;
import ljye.com.ljye.bean.Home_Carousels;
import ljye.com.ljye.bean.Home_Popular_Course;
import ljye.com.ljye.bean.Home_Stats_Teacher;
import ljye.com.ljye.utils.CommonViewHolder;
import ljye.com.ljye.utils.HttpUtils;
import ljye.com.ljye.utils.Utils;
import ljye.com.ljye.view.MyHorizontalScrollView;
import okhttp3.Request;
import okhttp3.Response;

import static ljye.com.ljye.App.client;


/**
 *
 */
public class Fragment_home extends Fragment implements View.OnClickListener {
    private View view;
    private LinearLayout region;
    private ImageView arrow;
    private LinearLayout head;
    private RightAdapter rightAdapter;
    private TextView etSearch;
    private Banner banner;
    private GridView gridView;
    private RecyclerView recyclerview;
    private RelativeLayout news;
    private TextView newsSpot;
    private ListView listview;


    private Intent intent;
    private List<String> address;
    private MyAdpapter adpapter;
    private List<String> school;
    private Gson gson;
    String[] images = new String[]{
            "http://ww3.sinaimg.cn/large/610dc034jw1f5d36vpqyuj20zk0qo7fc.jpg",
            "http://ww3.sinaimg.cn/large/610dc034jw1f5byokn81tj20dw0hiwfe.jpg",
            "http://ww1.sinaimg.cn/large/7a8aed7bjw1f2sm0ns82hj20f00l8tb9.jpg",
            "http://ww3.sinaimg.cn/large/7a8aed7bjw1f2x7vxkj0uj20d10mi42r.jpg",
            "http://ww4.sinaimg.cn/large/7a8aed7bjw1eyaov0c9z4j20iz0sg40t.jpg",};
    Integer[] images2 = {R.drawable.banner_1, R.drawable.banner_2, R.drawable.banner_3};
    private List<String> teachersList; //明星老师
    private List<String> recycler;//热门课程

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_home, null);
            initView();//初始化控件
            gson = new Gson();
            setData();
            region.setOnClickListener(this);//地区选择
            etSearch.setOnClickListener(this);//搜索
            initAutoBanner();//初始化轮播图
//            initRecyclerView();//初始化热门课程RecyclerView
            initstarsTeachers();//初始化明星老师
//            //明星老师
//            List<Course_Details.DataBean.TeachersBean> teachersList = data.getTeachers();
            setGridView(76,teachersList);//76指的是每个item的宽度 明星老师资料
            setRecyclerView();//热门课程
            //就近学
            adpapter = new MyAdpapter(school);
            listview.setAdapter(adpapter);
            setListViewHeight(listview);
        }
        return view;
    }
//热门课程
    private void setRecyclerView() {
        recyclerview.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        Popular_Course_Adapter adapter = new Popular_Course_Adapter(getActivity(), recycler);
        recyclerview.setAdapter(adapter);
        //点击事件
        adapter.setmOnItemClickLitener(new Popular_Course_Adapter.OnItemClickLitener() {
            @Override
            public void onItemClick(View view, int position) {
                intent=new Intent(getActivity(), Activity_Course_Details.class);
//                intent.putExtra("Course_Details", (Serializable)recycler.get(position));
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);

            }

            @Override
            public void onItemLongClick(View view, int position) {

            }
        });
    }

    //初始化明星老师
    private void initstarsTeachers() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder()
                            .url(HttpUtils.PATH + "/teacher/stars")
                            .build();
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Home_Stats_Teacher teacher = gson.fromJson(string, Home_Stats_Teacher.class);
                        final List<Home_Stats_Teacher.DataBean> data = teacher.getData();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (null!=data){
//                                    setGridView(76,data);
                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    //初始化热门课程RecyclerView
    private void initRecyclerView() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder()
                            .url(HttpUtils.PATH + "/course/hots")
                            .build();
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Home_Popular_Course course = gson.fromJson(string, Home_Popular_Course.class);
                        final List<Home_Popular_Course.DataBean> data = course.getData();
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
//                                if (null != data) {
//                                    recyclerview.setLayoutManager(new GridLayoutManager(getActivity(), 2));
//                                    Popular_Course_Adapter adapter = new Popular_Course_Adapter(getActivity(), data);
//                                    recyclerview.setAdapter(adapter);
//                                    //点击事件
//                                    adapter.setmOnItemClickLitener(new Popular_Course_Adapter.OnItemClickLitener() {
//                                        @Override
//                                        public void onItemClick(View view, int position) {
//                                            intent=new Intent(getActivity(), Activity_Course_Details.class);
//                                            intent.putExtra("Course_Details", (Serializable)data.get(position));
//                                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                                            startActivity(intent);
//
//                                        }
//
//                                        @Override
//                                        public void onItemLongClick(View view, int position) {
//
//                                        }
//                                    });
//                                }
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();




    }

    private void setData() {

        //地区选择
        address = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            address.add("洪山区" + i);
        }
        //校区
        school = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            school.add("早教中心" + i);
        }
        //明星老师
        teachersList = new ArrayList();
        for (int i = 0; i < 15; i++) {
            teachersList.add("老师" + i);
        }
        recycler = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            recycler.add("PAPA数学" + i);
        }
    }


    //明星老师
    private void setGridView(int width, final List<String> list) {
        int size = list.size();
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        float density = dm.density;
        int gridviewWidth = (int) (size * width * density);
        int itemWidth = (int) (width * density);//item宽度
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                gridviewWidth, LinearLayout.LayoutParams.FILL_PARENT);
        gridView.setLayoutParams(params); // 重点
        gridView.setColumnWidth(itemWidth); // 重点
        gridView.setHorizontalSpacing(0); // 间距
        gridView.setStretchMode(GridView.NO_STRETCH);
        gridView.setNumColumns(size); // 重点
        Home_Star_Teacher_GridViewAdapter starTeacherAdapter = new Home_Star_Teacher_GridViewAdapter(getActivity(), list);
        gridView.setAdapter(starTeacherAdapter);
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                TextView name = (TextView) view.findViewById(R.id.name);
                String s = name.getText().toString();
                Intent intent = new Intent(getActivity(), Activity_Teacher_Home.class);
//                Bundle bundle=new Bundle();
//                bundle.putString("teacher_id",list.get(i).getTeacher_id()+"");
//                intent.putExtras(bundle);
                startActivity(intent);

                Utils.showToast(getActivity(), "name:" + s);

            }
        });
    }


    //轮播图
    private void initAutoBanner() {
        banner.setBannerStyle(Banner.CIRCLE_INDICATOR);
        banner.setIndicatorGravity(Banner.CENTER);
        banner.isAutoPlay(true);//设置是否自动轮播（不设置则默认自动）
        banner.setDelayTime(2000);//设置轮播图片间隔时间（不设置默认为2000）

        banner.setImages(images2); //本地图片
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder()
                            .url(HttpUtils.PATH + "/index/carousels")
                            .build();
                    Response response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        String string = response.body().string();
                        Home_Carousels homeCarousels = gson.fromJson(string, Home_Carousels.class);
                        List<Home_Carousels.DataBean> data = homeCarousels.getData();
//                        int size = data.size();
                        final List<String> list=new ArrayList<String>();
                        for (int i = 0; i < data.size(); i++) {
                            Home_Carousels.DataBean dataBean = data.get(i);
                            String url = dataBean.getUrl();
                            list.add(url);
                        }
                        getActivity().runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                banner.setImages(list);
                            }
                        });
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

//        banner.setImages(images2);//系统使用Glide图片加载
//        //自定义图片加载框架
//        banner.setImages(images, new Banner.OnLoadImageListener() {
//            @Override
//            public void OnLoadImage(ImageView view, Object url) {
//
//                    Picasso.with(getActivity())
//                            .load(((String) url))
//                            .placeholder(R.drawable.banner_2)
////                            .fit()//填充全部
//                            .into(view);
//            }
//        });
        //设置点击事件，下标是从1开始
        banner.setOnBannerClickListener(new Banner.OnBannerClickListener() {//设置点击事件
            @Override
            public void OnBannerClick(View view, int position) {
                Utils.showToast(getActivity(), "你点击了：" + position);
            }
        });
    }

    private void initView() {
        etSearch = (TextView) view.findViewById(R.id.etSearch);
        banner = (Banner) view.findViewById(R.id.banner);
        region = (LinearLayout) view.findViewById(R.id.region);
        head = (LinearLayout) view.findViewById(R.id.head);//搜索头
        arrow = (ImageView) view.findViewById(R.id.arrow); //箭头
        news = (RelativeLayout) view.findViewById(R.id.news);//通知
        newsSpot = (TextView) view.findViewById(R.id.news_spot);//通知小红点
        gridView = (GridView) view.findViewById(R.id.grid);//横向明星老师
        listview = (ListView) view.findViewById(R.id.listview);
        recyclerview = (RecyclerView) view.findViewById(R.id.recyclerview);//热门课程


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.region://下拉地区
                initRegion();
                break;
            case R.id.etSearch://搜索
                intent = new Intent(getActivity(), Activity_Search.class);
                startActivity(intent);
                break;

            default:
                break;
        }

    }


    //透明背景方法
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getActivity().getWindow().setAttributes(lp);
    }

    private void initRegion() {
        //设置图片上
        arrow.setImageResource(R.drawable.arrow_top);

        //PopupWindow
        View contentView = View.inflate(getActivity(), R.layout.region_view, null);
        //弹出提示框
        final PopupWindow popupWindow = new PopupWindow(contentView, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT);
        //给PopWwindow设置背景
        popupWindow.setBackgroundDrawable(new ColorDrawable());
        //设置PopWwindow获取焦点    点popup外面的地方就会dismiss掉popupwindow
        popupWindow.setFocusable(true);
        //在指定的View下面弹出popupWindow
        popupWindow.showAsDropDown(head);
        backgroundAlpha(0.6f);//透明黑

        ListView lvLeft = (ListView) contentView.findViewById(R.id.lv_left);
        final ListView lvRight = (ListView) contentView.findViewById(R.id.lv_right);
        final LeftAdapter leftAdapter = new LeftAdapter(getActivity());
        leftAdapter.setData(address);
        lvLeft.setAdapter(leftAdapter);
        lvLeft.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                leftAdapter.checked(position);
                rightAdapter.setData(address);
                rightAdapter.notifyDataSetChanged();
                rightAdapter.checked(-1);
            }
        });
        rightAdapter = new RightAdapter(getActivity());
        rightAdapter.setData(address);
        lvRight.setAdapter(rightAdapter);
        lvRight.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                rightAdapter.checked(position);
                TextView textview = (TextView) view.findViewById(R.id.tv_name);
                String s = textview.getText().toString();
                //点击后上传地址刷新
                Toast.makeText(getActivity(), s, Toast.LENGTH_SHORT).show();
                popupWindow.dismiss();
            }
        });

        //当PopupWindow关闭的时候调用
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            @Override
            public void onDismiss() {
                arrow.setImageResource(R.drawable.arrow_down);
                backgroundAlpha(1.0f);//透明黑
            }
        });

    }

    public class MyAdpapter extends BaseAdapter {
        private List<String> mSchool;
        private int itemWidth;//单个条目的宽度
        private int scrollview_position = 0;//应该要滚动到的位置
        private GridViewAdapter adapter;
        private GridView grid;

        public MyAdpapter(List<String> school) {
            this.mSchool = school;
        }

        @Override
        public int getCount() {
            return mSchool == null ? 0 : mSchool.size();
        }

        @Override
        public Object getItem(int i) {
            return mSchool.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {

            CommonViewHolder holder = CommonViewHolder.createCVH(view, viewGroup, R.layout.item_school);
            RatingBar bar = holder.getView(R.id.rat, RatingBar.class);//评分星级 最高5级 可以半星
            TextView schoolName = holder.getTv(R.id.school_name);//学校名字
            LinearLayout school = holder.getView(R.id.school, LinearLayout.class);//点击进入机构主页
            bar.setRating(i);
            schoolName.setText(mSchool.get(i));
            //点击进入机构主页
            school.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Utils.showToast(getActivity(), "机构页" + i);
                    intent = new Intent(getActivity(), Activity_Institution_Home.class);
                    startActivity(intent);
                }
            });


            //---------------------下面代码千万别改动！！！--------------------------------
            final MyHorizontalScrollView myscrollvoew = holder.getView(R.id.myscrollvoew, MyHorizontalScrollView.class);
            grid = holder.getView(R.id.grid, GridView.class);
            //设置GridView数据
            setGridView(340);//340指的是item的宽度
            myscrollvoew.setOnScollChangedListener(new MyHorizontalScrollView.OnScollChangedListener() {
                @Override
                public void onScrollChanged(MyHorizontalScrollView scrollView, int x, int y, int oldx, int oldy) {

                    int scrollposition = x / itemWidth;//取整数
                    int a = x % itemWidth;//取余数
                    int position = a >= (itemWidth / 2) ? scrollposition + 1 : scrollposition;//需要移动到的位置
                    scrollview_position = position;
                }

                @Override
                public void isUp() {
                    Log.d("JJJ", "静止了");
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
//                        myscrollvoew.scrollTo(scrollview_position*itemWidth,0);非平滑
                            myscrollvoew.smoothScrollTo(scrollview_position * itemWidth, 0);

                        }
                    }, 500);
                }

                @Override
                public void isStatic() {
                    //一共会走四次 只能趋向于静止
                    Log.d("JJJ", "静止了");
                    new Handler().postDelayed(new Runnable() {
                        public void run() {
//                        myscrollvoew.scrollTo(scrollview_position*itemWidth,0);非平滑
                            myscrollvoew.smoothScrollTo(scrollview_position * itemWidth, 0);
                        }
                    }, 500);
                }
            });

            return holder.convertView;

        }
        //就近学
        private void setGridView(int width) {
            int size = mSchool.size();
            DisplayMetrics dm = new DisplayMetrics();
            getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
            float density = dm.density;
            int gridviewWidth = (int) (size * (width) * density);
            itemWidth = (int) (width * density);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    gridviewWidth, LinearLayout.LayoutParams.FILL_PARENT);
            grid.setLayoutParams(params); // 重点
            grid.setColumnWidth(itemWidth); // 重点
            grid.setHorizontalSpacing(0); // 间距
            grid.setStretchMode(GridView.NO_STRETCH);
            grid.setNumColumns(size); // 重点
            adapter = new GridViewAdapter(getActivity(), mSchool);
            grid.setAdapter(adapter);
            //点击查看课程
            grid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    Utils.showToast(getActivity(), "点击了" + i + "个课程");
                }
            });

        }
    }

    //解决ScrollView包裹listview后只显示一个条目问题
    public void setListViewHeight(ListView listView) {
        // 获取ListView对应的Adapter
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            return;
        }
        int totalHeight = 0;
        for (int i = 0, len = listAdapter.getCount(); i < len; i++) {
            // listAdapter.getCount()返回数据项的数目
            View listItem = listAdapter.getView(i, null, listView);
            // 计算子项View 的宽高
            listItem.measure(0, 0);
            // 统计所有子项的总高度
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        // listView.getDividerHeight()获取子项间分隔符占用的高度
        // params.height最后得到整个ListView完整显示需要的高度
        listView.setLayoutParams(params);
    }
}